package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String[].class)
public class StringArrayTypeHandler implements TypeHandler<String[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        // 将 String[] 转为 String 类型存入数据库中
        String s = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i, s);
    }

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        // 将String类型从数据中取出后，转换为 String[] 类型
        String stringType = resultSet.getString(s);
        String[] stringArrayType = objectMapper.readValue(stringType, String[].class);
        return stringArrayType;
    }

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        String stringType = resultSet.getString(i);
        String[] stringArrayType = objectMapper.readValue(stringType, String[].class);
        return stringArrayType;
    }

    @SneakyThrows
    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String stringType = callableStatement.getString(i);
        String[] stringArrayType = objectMapper.readValue(stringType, String[].class);
        return stringArrayType;
    }
}
